<?php

class Model{
        
    protected $db;

    public function __construct(){
        $this->db = new PDO("mysql:host=cpmy0027.servidorwebfacil.com;dbname=t81421_bd","t81421_trix","#CR../trix");
        #$this->db = new PDO("mysql:host=mysql.intranet;dbname=jbfm","hpjbfm","jbfm0007");
        $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }

    public function insert( $tabela, Array $dados){

        foreach ($dados as $indice => $val){
            $campos[] = $indice;
            $valores[] = $val;
        }

        # obtem os valores 
        $campos  = implode(", ", $campos);
        $valores = "'".implode("','", $valores)."'";
        
        # Monta a query 
        $query = $this->db->query("INSERT INTO `{$tabela}` ({$campos}) VALUES({$valores});");
        
            # retorna 
        return $query;
        
    }
    
    public function insert_sql($sql){
        
        # Monta a query 
        $query = $this->db->query($sql);
        
        # retorna 
        return $query;
        
    }

    public function read( $tabela, $where, $order, $limite, $habilitar_cache ){

        # obtem os valores
        
        $where = ( ($where != null) ? "WHERE {$where}" : "" );

        $order = ( ($order != null) ? "ORDER BY {$order}" : "" );

        $limite = ( ($limite != null) ? "LIMIT {$limite}" : "" );
        $cache = ( ($habilitar_cache == null) ? "SQL_CACHE" : "" );
        #echo "SELECT * FROM `{$tabela}` {$where} {$order} {$limite} ;";
        
        try
        {
            $query = $this->db->query("SELECT {$cache} * FROM `{$tabela}` {$where} {$order} {$limite} ;");
            $params = $query->fetchAll(PDO::FETCH_ASSOC);
            
            # retorna 
            return $params;
            
            
           
        }
            catch (PDOException $i)
            {
                # se houver exceção, exibe
                # print "<code>" . $i->getMessage() . "</code>";
                return false;
            }
        
        
    }
    
    public function read_min_or_max( $tabela, $min_max, $campo, $where, $order, $limite, $habilitar_cache){


        $where = ( ($where != null) ? "WHERE {$where}" : "" );

        $order = ( ($order != null) ? "ORDER BY {$order}" : "" );

        $limite = ( ($limite != null) ? "LIMIT {$limite}" : "" );
        
        $cache = ( ($habilitar_cache == null) ? "SQL_CACHE" : "" );
        # echo "SELECT {$min_max}({$campo}) FROM `{$tabela}` {$where} {$order} {$limite} ;";
        try
        {
            $query = $this->db->query("SELECT {$cache} {$min_max}({$campo}) FROM `{$tabela}` {$where}{$order}{$limite};");
            $params = $query->fetchAll(PDO::FETCH_ASSOC);
            
            # retorna 
            return $params;

            
            
        }
            catch (PDOException $i)
            {
                # se houver exceção, exibe
                # print "<code>" . $i->getMessage() . "</code>";
                return false;
            }
        
        
    }
    
    public function read_join($dados){
        try
        {
        
            $query = $this->db->query("{$dados};");  
            
            $params = $query->fetchAll(PDO::FETCH_ASSOC);

            # retorna
            return $params;
            
        
        }catch(PDOException $i){
           # se houver exceção, exibe
           # print "<code>" . $i->getMessage() . "</code>";
            return false;
        }
    }
    
    public function update_sql($dados){
        try
        {
        
            $query = $this->db->query("{$dados};");  
            
            # retorna 
            return true;
            
        
        }catch(PDOException $i){
           #se houver exceção, exibe
           #print "<code>" . $i->getMessage() . "</code>";
            return false;
        }
    }
    
    public function read_filtros($dados){
        try
        {
        
            $query = $this->db->query("{$dados};");  
            
            $params = $query->fetchAll(PDO::FETCH_ASSOC);

            # retorna
            return $params;
            
        
        }catch(PDOException $i){
           #se houver exceção, exibe
           #print "<code>" . $i->getMessage() . "</code>";
            return false;
        }
    }

    public function update($tabela, Array $dados, $where){

        foreach($dados as $indice => $valor){
            $campos[] = "{$indice} = '{$valor}'";
        }

        $campos = implode(", ",$campos);
        #echo "UPDATE `{$tabela}` SET {$campos} WHERE {$where};";
        #exit;
        try
        {
        
            $query = $this->db->query("UPDATE `{$tabela}` SET {$campos} WHERE {$where};");
            
            # retorna
            return $query;
            

        }catch(PDOException $i){
           #se houver exceção, exibe
           print "<code>" . $i->getMessage() . "</code>";
        }

    }
    
    public function delete($tabela, $where){
        $query = ($this->db->query("DELETE FROM `{$tabela}` WHERE {$where}; ")) ? true : false;
        
        /* retorna */
        return $query;        

    }
    
        public function paginar($maximo, $pagina, $url , $tabela, $where, $order, $habilitar_cache){
        
            
                    $where = ( ($where != null) ? "WHERE {$where}" : "" );
                    $order = ( ($order != null) ? "ORDER BY {$order}" : "" );
                    $cache = ( ($habilitar_cache == null) ? "SQL_CACHE" : "" );
            
            
                    $max=$maximo;
                    if ($pagina == "")
                    $pagina=1;

                    $inicio = $pagina - 1;
                    $inicio = $max * $inicio;
                    
                    $sql="SELECT {$cache} COUNT(*) as total FROM `{$tabela}` {$where} {$order};";
                    $select = $this->read_join($sql);
                    $total = $select[0]['total'];
                    
                    if ($total == 0)
                    $paginacao = "Nenhum registro encontrado!";
                    else
                    {
                    
                        $sql="SELECT * FROM `{$tabela}` {$where} {$order} LIMIT $inicio,$max;";
                        $select = $this->read_join($sql);
                    
                        
                    }
                    // Calculando pagina anterior
                    $menos = $pagina - 1;
                    
                    // Calculando pagina posterior
                    $mais = $pagina + 1;
                    $pgs = ceil($total / $max);
                    
                    $paginacao = "";
                    
                    if($pgs > 1 )
                    {
                        if($menos>0)
                        $paginacao .= "<a href='$url/pagina/$menos' class='ExLink'>Anterior</a> ";
                    
                        if (($pagina-4) < 1 )
                        $anterior = 1;
                        else
                        $anterior = $pagina-4;
                    
                        if (($pagina+4) > $pgs )
                        $posterior = $pgs;
                        else
                        $posterior = $pagina + 4;
                    
                        for($i=$anterior;$i <= $posterior;$i++){
                        if($i != $pagina){
                        $paginacao .= " <a href='$url/pagina/$i' class='ExLink'>$i</a>";
                        }else{
                        $paginacao .= " <span style='font-size:14px;font-weight:bold;' class='ExLink'>$i</span>";
                    }
                    
                    }
                        if($mais <= $pgs){
                        $paginacao .= " <a href='$url/pagina/$mais' class='ExLink'>Próxima</a>";
                        
                        }
                    }

                    
                   $array["paginacao"] = $paginacao;
                   $array["dados"] = $select;
                   return $array; 
    }
    


        
        
        
        
}
?>
